import {
  api,
  util,
} from '../../../../js/util';
import {
  router
} from '../../../../js/router';
import {
  theme,
} from '../../../../js/modules/theme';
import {
  list,
} from '../../../../js/modules/mall';
import {
  cart
} from '../../../../js/modules/order';
import authorize from '../../../../js/modules/authorize';
import {
  config
} from "../../../../js/modules/gloab";
import BasePage from '../../../../js/common/base-page'
import { hideTabbar } from '../../../../js/compatible';
import { getSystemInfoSync, isEmpty } from '../../../../js/newUtil';
const app = getApp()
BasePage({
  pageKey: "classify",
  validateLogin: app.dns.fkId != app.dns.proprietorId,
  /**
   * 页面的初始数据
   */
  data: {
    tabKey: "classify_" + app.dns.proprietorId,
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    mainColor: api.titleColor || "#e56b14", //主题色
    selectedCategoryId: 0,
    firstCategory: [],
    categoryChild: {
      bannerImage: "",
      bannerLink: "",
      hasBanner: false,
      categoryExtends: [],
    },
    headerBg: "",
    loopCount: 0,
    visitTimer: null,
    isIphoneX: app.globalData.isIphoneX,
    tabindex: -1,
    isShowBrandClass: true,
    asideHeight: 1200, // 侧边栏高度
    viewStyle: 0, // 显示的样式 0: 有侧边栏 1：无侧边栏/title居中 2: 抽屉模式
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.initTabBar();
    this.getWholesaleConfig();
    this.setScrollHeight()
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Wholesale",
      function (model) {
        let AppTemplateConfig = model.AppTemplateConfig || {}
        that.setData({
          isShowBrandClass: model.NotShowBrandClass == false,
          viewStyle: AppTemplateConfig.TemplateIndex || 0,
          BGColorForMobile: model.BGColorForMobile
        });
      });
  },
  /**
   * 加载类别 
   * */
  loadFirstCategory(callback) {
    var that = this;
    list.loadCategories(0, function (content) {
      let category = content;
      if (callback && typeof (callback) == 'function') {
        callback(category);
      }
    });
  },
  loadChildCategory(parentId, callback) {
    var that = this;
    list.loadChildCategory(parentId, function (content) {
      that.setData({
        categoryChild: content
      }, () => {
        that.onPageScrollToTop();
      });
      if (callback && typeof (callback) == "function") {
        callback(content)
      }
    });
  },
  loadBrands() {
    var that = this;
    list.loadBrands(function (content) {
      var brand = content;
      brand.map((item, i) => {
        item.CateName = item.Name;
        item.CateImg = item.Logo;
      });
      var cd = {
        bannerImage: "",
        hasBanner: false,
        bannerLink: "",
        categoryExtends: [],
      };
      cd.categoryExtends.push({
        Name: "所有品牌",
        Source: brand,
        Type: 1
      })
      that.setData({
        categoryChild: cd
      }, () => {
        that.onPageScrollToTop();
      });
    });
  },
  onSelectedCategory(e) {
    var that = this;
    var o = e.currentTarget.dataset;
    var selectedCategoryId = o.categoryid;
    this.setData({
      selectedCategoryId: selectedCategoryId
    });
    if (selectedCategoryId > 0) {
      this.loadChildCategory(selectedCategoryId, function (content) {
        if (content.categoryExtends.length == 0) {
          app.globalData.product_list.cid = selectedCategoryId;
          app.globalData.product_list.bid = 0;
          router.navigate({
            path: "productList"
          });
        }
      });
    } else {
      this.loadBrands();
    }
  },
  onSearchProduct(e) {
    var o = e.currentTarget.dataset;
    var id = o.id;
    var t = o.type;
    var types = o.types;
    if (t == 1) {
      app.globalData.product_list.cid = this.data.selectedCategoryId;
      app.globalData.product_list.bid = id + "";
      app.globalData.product_list.typeId = types;
    } else {
      app.globalData.product_list.bid = 0;
      app.globalData.product_list.cid = id;
      app.globalData.product_list.typeId = types;
    }
    router.navigate({
      path: "productList"
    });
  },
  /**
   * 获取侧边栏高度
   */
  setScrollHeight() {
    let that = this
    let query = wx.createSelectorQuery()
    query.select('.search').fields({
      size: true
    }).exec((res) => {
      let system = getSystemInfoSync()
      let height = 0
      if (!isEmpty(res)) {
        let searchHeight = res[0].height
        height = system.windowHeight - searchHeight
        height = height * system.rpxRate
      } else {
        height = system.rpxHeight - 112
      }
      let isIphoneX = this.data.isIphoneX
      if (isIphoneX) {
        height = height - 130
      } else {
        height = height - 100
      }
      that.setData({
        asideHeight: height
      })
    })
  },
  /**
   * 搜索
   */
  bindSearch(e) {
    var that = this;
    app.globalData.product_list.index_search_keyword = e.detail;
    router.navigate({
      path: "productList"
    });
    let id = `#suggestion`
    let component = this.selectComponent(id)
    component.hide()
    component.addKeyword(e.detail)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    //隐藏原生底部导航
    hideTabbar()
    var tabindex = app.getTabBarindex();
    this.setData({
      tabindex: tabindex
    });
    if (app.globalData.pageRefresher.classify) {
      // 登录/退出登录后，重新刷新页面，防止显示上个用户所对应的目录
      app.globalData.pageRefresher.classify = false
      wx.reLaunch({
        url: '/pages/store/purchase/classify/classify'
      })
      return
    }
    this.isCanVisit(() => {
      this.setData({
        headerBg: api.titleColor || "#e56b14"
      });
      let entity = authorize.getEntity();
      let fkId = 0;
      if (entity) {
        fkId = entity.fkId;
      }
      this.data.fkId = fkId;
      if (this.data.tabKey != "classify_" + app.dns.proprietorId + "_" + fkId) {
        this.data.tabKey = "classify_" + app.dns.proprietorId + "_" + fkId;
        this.loadFirstCategory(function (categorys) {
          // 只有第一种样式需要去将品牌数据放在最前
          if (that.data.isShowBrandClass && that.data.viewStyle == 0) {
            categorys.unshift({
              Id: 0,
              CateName: '品牌',
              ParentId: 0,
              TypeId: 0
            });
          }
          let firstCategoryId = categorys.length > 0 ? categorys[0].Id : 0;
          that.setData({
            firstCategory: categorys,
            selectedCategoryId: firstCategoryId
          });
          if (firstCategoryId > 0) {
            that.loadChildCategory(firstCategoryId);
          } else if (that.data.isShowBrandClass && that.data.viewStyle == 0) {
            that.loadBrands();
          }
        });
      }
      //获取购物车数量
      cart.get_cart_count();
    })
  },
  isCanVisit(callback) {
    let that = this;
    this.clearVisitTimer();
    this.data.visitTimer = setTimeout(() => {
      if (api.isLoginVisit != undefined) {
        that.data.loopCount = 0;
        if ((app.dns.fkFlag != app.dns.proprietor && app.dns.fkId > 0 && app.dns.proprietorId == 0 && !authorize.isLogin('store')) || (api.isLoginVisit && !authorize.isLogin('store'))) {
          authorize.redirect('store');
        } else {
          callback();
        }
      } else if (that.data.loopCount < 60) {
        that.data.loopCount++;
        that.isCanVisit(callback);
      }
    }, 100)
  },
  clearVisitTimer() {
    if (this.data.visitTimer != null) {
      clearTimeout(this.data.visitTimer);
      this.data.visitTimer = null;
    }
  },
  /**
   * 替换链接 
   */
  linkTo(e) {
    var url = e.currentTarget.dataset.url || e.detail.url;
    theme.linkTo(url);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.data.loopCount = 0;
    this.clearVisitTimer();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.selectedCategoryId > 0) {
      this.loadChildCategory(this.data.selectedCategoryId)
    } else if (this.data.isShowBrandClass && that.data.viewStyle == 0) {
      this.loadBrands()
    } else {
      let firstCategoryId = this.data.firstCategory.length > 0 ? this.data.firstCategory[0].Id : 0;
      this.setData({
        selectedCategoryId: firstCategoryId
      });
      this.loadChildCategory(firstCategoryId);
    }
    this.onShow();
    wx.stopPullDownRefresh();
  },

  /**
   * 顶部搜索框获取焦点
   */
  searchFocus() {
    let id = `#suggestion`
    let component = this.selectComponent(id)
    component.show()
  },

  /**
   * 点击 历史/推荐 中的内容搜索
   * @param {*} e 
   */
  suggestionSearch(e) {
    this.bindSearch({
      detail: e.detail.keyword
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 页面滚动到顶部
   */
  onPageScrollToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
  },
  /**
   * 展开/收起一级分类
   */
  toggleAccordion (e) {
    let index = e.currentTarget.dataset.index
    let firstCategory = this.data.firstCategory || []
    if (isEmpty(firstCategory[index].isNarrow)) {
      firstCategory[index].isNarrow = false
    }
    firstCategory[index].isNarrow = !firstCategory[index].isNarrow
    this.setData({
      firstCategory
    })
  },
})